package com.mqb.config.mixin;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.MissingNode;
import com.mqb.model.Role;
import com.mqb.model.User;

import java.io.IOException;
import java.util.List;

/**
 * @author mqb
 * @date 2021/4/7 10:13
 */
class UserDeserializer extends JsonDeserializer<User> {

    @Override
    public User deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ObjectMapper mapper = (ObjectMapper) p.getCodec();
        JsonNode jsonNode = mapper.readTree(p);
        List<Role> roles = mapper.convertValue(jsonNode.get("roles"), new TypeReference<List<Role>>() {
        });
        JsonNode password = readJsonNode(jsonNode, "password");
        User result = new User();
        result.setId(readJsonNode(jsonNode, "id").asLong())
                .setUsername(readJsonNode(jsonNode, "username").asText())
                .setPassword(password.asText(""))
                .setAccountNonExpired(readJsonNode(jsonNode, "accountNonExpired").asBoolean())
                .setAccountNonLocked(readJsonNode(jsonNode, "accountNonLocked").asBoolean())
                .setCredentialsNonExpired(readJsonNode(jsonNode, "credentialsNonExpired").asBoolean())
                .setEnabled(readJsonNode(jsonNode, "enabled").asBoolean())
                .setRoles(roles);

        if(password.asText(null) == null){
            result.eraseCredentials();
        }

        return result;
    }

    private JsonNode readJsonNode(JsonNode jsonNode, String field) {
        return jsonNode.has(field) ? jsonNode.get(field) : MissingNode.getInstance();
    }
}
